package com.principles.behavior.command;

/**
 * @Description 命令模式————是一种行为设计模式，它可以将请求转化为一个包含与请求相关的所有信息的独立对象。该转化让你能根据不同的请求将方法参数化、延迟请求执行或将其放入队列中，且能实现可撤销操作。
 * @Date 2025/1/28 14:29
 **/
public class CommandPattern {
// Client 客户端远程调用代码
    public static void main(String[] args) {
        Light light = new Light();  // 创建接收者对象

        // 创建命令对象
        Command lightOn = new LightOnCommand(light);
        Command lightOff = new LightOffCommand(light);

        RemoteControl remote = new RemoteControl();  // 创建调用者对象

        // 打开灯
        remote.setCommand(lightOn);
        remote.pressButton();

        // 关闭灯
        remote.setCommand(lightOff);
        remote.pressButton();
    }
}

// Command接口
interface Command {
    void execute();
}

// Receiver 接收者类
class Light {
    public void turnOn() {
        System.out.println("Light is ON");
    }

    public void turnOff() {
        System.out.println("Light is OFF");
    }
}

// 具体命令类 - 打开灯
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}

// 具体命令类 - 关闭灯
class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }
}

// Invoker 调用者类
class RemoteControl {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        if (command != null) {
            command.execute();
        }
    }
}

